package com.tongsys.server.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tongsys.server.utils.RtnUtils;
import com.tongsys.server.utils.RtnCode;
import io.swagger.annotations.ApiModel;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
@ApiModel("匿名(未认证)的用户 访问无权限资源时 处理器类")
public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        //设置响应编码
        response.setContentType("application/json;charset=utf-8");
        //创建输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //封装为对象，并转换成json ，并消除循环引用
        String res = JSON.toJSONString(RtnUtils.err().code(RtnCode.NO_LOGIN).msg("匿名用户，无权限访问"), SerializerFeature.DisableCircularReferenceDetect);
        //输出流，写出json
        outputStream.write(res.getBytes(StandardCharsets.UTF_8));
        //情况缓存区，将数据完整写内存中
        outputStream.flush();
        //关闭输出流
        outputStream.close();
    }
}
